package com.roc.web.action.terminal;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.WareHouseSNStatisticsInfo;
import com.roc.service.IExcelService;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

@Component
@Scope("prototype")
@Namespace("/wareHouSnStatics")
public class WareHouseSNStatisticsAction extends PaginationBaseAction {
	
	private Logger logger=LogManager.getLogger(WareHouseSNStatisticsAction.class);
	
	private WareHouseSNStatisticsSearchCondition searchCondition;
	
	private InputStream excelFile;

	@Autowired
	IPageService pagenitionService;
	
	@Autowired
	IExcelService excelService;
	
 
	@Action(value = "init", results = { @Result(name = "success", location = "/pages/terminal/wareHouSnStatics.jsp"),
			@Result(name = "error", location = "/error.jsp")
	})
	public String init() throws Exception{
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		/*
		Map<String, String> map=powerInfoService.queryRealIdByOpId(op.getSuperiorId(), op.getRoleType(), op.getId(), op.getOrgCode());
        String superRole= map.get("superRole");*/
        // 非系统管理员/收单事业部/付临门受理市场总部，不允许登陆
		if( !op.getRoleType().equals(Role.SYSTEM.getCode())
			&&  !Constant.SHOUDANSHIYEBU_ID.equals( String.valueOf( op.getId()) )
			&& !( op.getRealName().contains( Constant.SHOULI_SHICHANG_ZONGBU_NAME ) 
					&& Constant.SHOUDANSHIYEBU_ID.equals( String.valueOf(op.getSuperiorId()) )
					&& op.getRoleType().equals(Role.O_MANAGER.getCode()) ) 	) {
			addActionError("当前登录账号无权限访问!!!");
			return ERROR;
		}
		searchCondition = new WareHouseSNStatisticsSearchCondition();
		searchCondition.setEndBrandDate(Constance.formatDate("yyyyMMdd"));
		return SUCCESS;
	}
	
	@Action(value = "queryWareHouSnStatics", results = { @Result(name = "success", location = "/pages/terminal/wareHouSnStatics.jsp"),@Result(name = "error", location = "/error.jsp")
    })
	public String queryWareHouSnStatics(){
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

		try {
			if(searchCondition==null){
				searchCondition=(WareHouseSNStatisticsSearchCondition)getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition=new WareHouseSNStatisticsSearchCondition();
				}
			}/*
			Map<String, String> map=powerInfoService.queryRealIdByOpId(op.getSuperiorId(), op.getRoleType(), op.getId(), op.getOrgCode());
	        String superRole= map.get("superRole");*/
	        // 非系统管理员/收单事业部/付临门受理市场总部，不允许登陆
			if( !op.getRoleType().equals(Role.SYSTEM.getCode())
				&&  !Constant.SHOUDANSHIYEBU_ID.equals( String.valueOf( op.getId()) )
				&& !( op.getRealName().contains( Constant.SHOULI_SHICHANG_ZONGBU_NAME ) 
						&& Constant.SHOUDANSHIYEBU_ID.equals( String.valueOf(op.getSuperiorId()) )
						&& op.getRoleType().equals(Role.O_MANAGER.getCode()) ) 	) {
				addActionError("当前登录账号无权限访问!!!");
				return ERROR;
			}
			if( !Constance.isNotEmpty( searchCondition.getEndBrandDate() ) ) {
				addActionError("绑定日期不能为空!!!");
				return ERROR;
			}
			boolean isSlsc = false;
			// 如果是受理市场总部，只查直营数据
			if( op.getRealName().contains( Constant.SHOULI_SHICHANG_ZONGBU_NAME ) 
					&& Constant.SHOUDANSHIYEBU_ID.equals( String.valueOf(op.getSuperiorId()) )
					&& op.getRoleType().equals(Role.O_MANAGER.getCode()) ) {
				isSlsc = true;
			}
			searchCondition.setSlsc(isSlsc);
			
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
			dealTheSearchRsList(searchRsList);
			
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
		//	org();
			setSearchToConditionSession(searchCondition);
			addActionMessage("当前条件下统计到【"+rows+"】条记录");
		} catch (Exception e) {
			logger.error("查询仓库SN统计信息异常："+e.getMessage());
		}
		return SUCCESS;
	}
	
	@Action(value="exportWareHouSnStatics",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/vnd.ms-excel", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=${excelName}.xlsx",
			            "bufferSize", "1024*3" }),@Result(name="error",location="/pages/terminal/wareHouSnStatics.jsp") })
	public String exportWareHouSnStatics(){
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

		try {
			if(searchCondition==null){
				searchCondition=(WareHouseSNStatisticsSearchCondition)getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition=new WareHouseSNStatisticsSearchCondition();
				}
			}
			/*
			Map<String, String> map=powerInfoService.queryRealIdByOpId(op.getSuperiorId(), op.getRoleType(), op.getId(), op.getOrgCode());
	        String superRole= map.get("superRole");*/
	        // 非系统管理员/收单事业部/付临门受理市场总部，不允许登陆
			if( !op.getRoleType().equals(Role.SYSTEM.getCode())
				&&  !Constant.SHOUDANSHIYEBU_ID.equals( String.valueOf( op.getId()) )
				&& !( op.getRealName().contains( Constant.SHOULI_SHICHANG_ZONGBU_NAME ) 
						&& Constant.SHOUDANSHIYEBU_ID.equals( String.valueOf(op.getSuperiorId()) )
						&& op.getRoleType().equals(Role.O_MANAGER.getCode()) ) 	) {
				addActionError("当前登录账号无权限访问!!!");
				return ERROR;
			}
			boolean isSlsc = false;
			// 如果是受理市场总部，只查直营数据
			if( op.getRealName().contains( Constant.SHOULI_SHICHANG_ZONGBU_NAME ) 
					&& Constant.SHOUDANSHIYEBU_ID.equals( String.valueOf(op.getSuperiorId()) )
					&& op.getRoleType().equals(Role.O_MANAGER.getCode()) ) {
				isSlsc = true;
			}
			searchCondition.setSlsc(isSlsc);
			if( !Constance.isNotEmpty( searchCondition.getEndBrandDate() ) ) {
				addActionError("绑定日期不能为空!!!");
				return ERROR;
			}
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), rows);
			}
			dealTheSearchRsList(searchRsList);
			SXSSFWorkbook work=excelService.exportWareHouSnStatics(searchRsList);

			ByteArrayOutputStream output = new ByteArrayOutputStream();  
			work.write(output);  
			   
			byte[] ba = output.toByteArray();  
			excelFile = new ByteArrayInputStream(ba);  
			output.flush();  
			output.close();
			
		} catch (Exception e) {
			logger.error("导出仓库SN统计信息异常："+e.getMessage());
		}
		return SUCCESS;
	}
	
	private void dealTheSearchRsList( List<Object> list ) {
    	List<Object> tempList=new ArrayList<Object>();
		for(Object object:list){
			
			Object[] obj = (Object[])object ; 
			WareHouseSNStatisticsInfo temp = new WareHouseSNStatisticsInfo();

			temp.setCompanyName ( Constance.Null2EmptyTrim( obj[0] ) ) ;// 分公司

			String brandCode = obj[1] + "";
			String nameCode = obj[2] + "";
			
			temp.setPosBrand(ConfigMerinfoUtil.getPosBRAND(brandCode)) ;// 厂商
			temp.setPosName(ConfigMerinfoUtil.getPosMODEL(nameCode , brandCode)) ;// 名称
			
			temp.setAllCount ( Constance.Null2EmptyTrim( obj[3] ) ) ;// 总领数
			temp.setAllBrandCount ( Constance.Null2EmptyTrim( obj[4] ) ) ;// 总绑定数量
			temp.setTdBrandCount ( Constance.Null2EmptyTrim( obj[5] ) ) ; // 当日绑定数量
			tempList.add(temp);
		}
		searchRsList=tempList;
		
	}
	

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
		
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_WARE_HOUSE_SN_STATISTICS, searchCondition);
		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (WareHouseSNStatisticsSearchCondition)getSession().getAttribute(SEARCH_SESSION_WARE_HOUSE_SN_STATISTICS);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE+"";
	}

	public WareHouseSNStatisticsSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(WareHouseSNStatisticsSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}
	
	
	public String getExcelName() {
		String excelName="仓库SN统计-"+Constance.formateDate();
		 
			try {
				excelName = new String(excelName.getBytes(),"ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.info("生成excel名称失败了！");
			}
		 
		return  excelName;
		
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}



}
